package com.sample.rx3

import android.os.Bundle
import android.text.TextUtils
import android.view.MenuItem
import androidx.activity.result.ActivityResultLauncher
import androidx.appcompat.app.AppCompatActivity
import androidx.fragment.app.Fragment
import androidx.viewpager2.widget.ViewPager2
import com.google.android.material.navigation.NavigationBarView
import com.sample.rx3.base.IFrag2ActImpl
import com.sample.rx3.databinding.ActivityTestBinding
import com.sample.rx3.fragment.BlankFragment

class TestActivity : AppCompatActivity(), IFrag2ActImpl,
    NavigationBarView.OnItemSelectedListener, AndPerMission.SingleCallback {
    private val binding by lazy { ActivityTestBinding.inflate(layoutInflater) }
    private lateinit var singleLauncher: ActivityResultLauncher<String>
    private var fragments: MutableList<Fragment> = ArrayList()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(binding.root)
        singleLauncher = AndPerMission.single(this, this)

        fragments.add(BlankFragment.newInstance("memory"))
        fragments.add(BlankFragment.newInstance("location"))
        fragments.add(BlankFragment.newInstance("phone"))
        fragments.add(BlankFragment.newInstance("camera"))
        binding.viewPager.adapter = ViewPager2Adapter(this, fragments)
        binding.navigation.setOnItemSelectedListener(this)
        binding.viewPager.registerOnPageChangeCallback(object : ViewPager2.OnPageChangeCallback() {
            override fun onPageSelected(position: Int) {
                super.onPageSelected(position)
                when (position) {
                    0 -> binding.navigation.selectedItemId = R.id.navigation_home
                    1 -> binding.navigation.selectedItemId = R.id.navigation_dashboard
                    2 -> binding.navigation.selectedItemId = R.id.navigation_notifications
                    3 -> binding.navigation.selectedItemId = R.id.navigation_bind
                }
            }
        })
    }

    override fun onNavigationItemSelected(item: MenuItem): Boolean {
        when (item.itemId) {
            R.id.navigation_home -> {
                binding.viewPager.currentItem = 0
                return true
            }

            R.id.navigation_dashboard -> {
                binding.viewPager.currentItem = 1
                return true
            }

            R.id.navigation_notifications -> {
                binding.viewPager.currentItem = 2
                return true
            }

            R.id.navigation_bind -> {
                binding.viewPager.currentItem = 3
                return true
            }
        }
        return false
    }

    override fun onFrag2Act(tag: String?, objTag: Any?) {
        if (TextUtils.equals("camera", tag)) {
            singleLauncher.launch(AndPerMission.CAMERA)
        }
    }

    override fun onSingleCallback(successful: Boolean) {

    }
}